from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings
from django.shortcuts import redirect
class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """如果用户已经登录，则request里赋值"""
        user_id = request.session.get('user_id', 0)  # 如果获取不到值，则user_id=0
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.manager = user_object

        customer_name = request.session.get('customer_name', 0)  # 如果获取不到值，则user_id=0
        customer_object = models.CustomerInfo.objects.filter(username=customer_name).first()
        request.customer = customer_object

        path = request.path_info
        if path.startswith('/user/'):
            # 顾客模块
            if request.path_info in settings.WHITE_URL_LIST2:
                return
            if not request.customer:
                return redirect(('/user/login/'))
            else:
                return
        # 白名单，不用登陆就可以访问
        if request.path_info in settings.WHITE_URL_LIST:
            return
        if not request.manager:
            return redirect('/login/')
        else:
            return
